package cn.edu.whu.forecast.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Slf4j
public class HttpClientUtil {

    /**
    * 发送get请求
    * @author fullangleblank
    * @since 2022/6/24
    */
    public static String doGet(String url){

        String result="";
        try {
            // 根据地址获取请求
            HttpGet request = new HttpGet(url);//这里发送get请求
            // 获取当前客户端对象
            HttpClient httpClient = new DefaultHttpClient();
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(request);

            // 判断网络连接状态码是否正常(0--200都数正常)
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result= EntityUtils.toString(response.getEntity(),"utf-8");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
        //....result是用户信息,站内业务以及具体的json转换这里也不写了...
    }
    /**
     * 发送HTTP POST请求
     * @param url        请求url
     * @param parameters post参数
     * @return 返回数据
     */
    public static String doPost(String url, Map<String, Object> parameters) throws IOException {
        HttpPost post = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //参数设定的是HTTP连接的超时时间，单位为毫秒
//            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
            //设定的是HTTP连接成功后，等待读取数据或者写数据的最大超时时间，单位为毫秒
//            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

            post = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000).setConnectionRequestTimeout(1000)
                    .setSocketTimeout(1000 * 60 * 60 * 2).build();
            post.setConfig(requestConfig);

            // 构造消息头
            post.setHeader("Connection", "Close");
            //post.setHeader("Content-Type", "application/x-www-form-urlencoded");
            post.setHeader("Content-type", "application/json; charset=utf-8");

            if (parameters != null) {
                StringEntity entity = new StringEntity(JSON.toJSONString(parameters), StandardCharsets.UTF_8);
                entity.setContentEncoding("UTF-8");
                // 发送Json格式的数据请求
                entity.setContentType("application/json");
                post.setEntity(entity);
            }

//            ArrayList<BasicNameValuePair> pp = new ArrayList<BasicNameValuePair>();
//            for (String key : parameters.keySet()) {
//                pp.add(new BasicNameValuePair(key, parameters.get(key)));
//            }
//            post.setEntity(new UrlEncodedFormEntity(pp));

            CloseableHttpResponse response;
            response = httpClient.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                if (statusCode == HttpStatus.SC_METHOD_FAILURE) {
                    return null;
                }
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("调用python接口出错" + statusCode);
                return null;
            }
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (post != null) {
                try {
                    post.releaseConnection();
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 异步发送HTTP POST请求
     *
     * @param url        请求url
     * @param parameters post参数
     * @return 返回CompletableFuture对象，可以查询返回结果
     */
    public static CompletableFuture<String> doAsyncPost(String url, Map<String, Object> parameters) throws IOException {
        return CompletableFuture.supplyAsync(() -> {
            try {
                return doPost(url, parameters);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        });
    }


//    /**
//     * 异步发送forecast请求
//     * @param url 请求url
//     * @param parameters post参数
//     * @param users post参数
//     * @return 返回CompletableFuture对象，可以查询返回结果，
//     */
//    public static CompletableFuture<String> machineLearningForecast(String url, Map<String, Object> parameters, List<String> users, String userName) throws IOException {
//        System.out.println(users);
//        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
//            try {
//                String result = doPost(url, parameters);
//                System.out.println("Remove!");
//                users.remove(userName);
//                System.out.println(users);
//                return result;
//            } catch (IOException e) {
//                e.printStackTrace();
//                return null;
//            }
//        });
//        return future;
//    }
//
//    /**
//     * 异步发送forecast请求
//     *
//     * @param url        请求url
//     * @param parameters post参数
//     * @param users      post参数
//     * @return 返回CompletableFuture对象，可以查询返回结果，
//     */
//    public static void machineLearningForecast(String url, Map<String, Object> parameters, List<String> users, String userName) throws IOException {
//        System.out.println("机器学习预报前:" + users);
//        final CountDownLatch cdl = new CountDownLatch(1);
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();
//        // 第一个线程执行doPost方法
//        threadPool.execute(() -> {
//                    try {
//                        doPost(url, parameters);
//                    } catch (Throwable e) {
//                        e.printStackTrace();
//                    }finally {
//
//                    }
//                }
//        );
//        threadPool.shutdown();
//    }
}
